package de.hs_rm.mmk.group_talk.activities;

import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;

import de.hs.mmk.group_talk.audio_managing.AudioRecorder;
import de.hs.mmk.group_talk.audio_managing.AudioStreamer;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class UserView extends Activity{
        String[] names;
        int players = 1;
        AudioRecorder recorder = null;
        AudioStreamer streamer = null;
        Communication comm;
        String nickname;
        String serverhost; 
    	int serverport;
    	String myport;
        String groupname;
        String speechMod;
        DatagramSocket mySocket;
        AlertDialog.Builder builder;
        ListView lv;
        ArrayAdapter<String> arrayAdapter;
        MemberListViewInterface memberList;
        StreamHandler streamHandler;
        
        @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.talkmaster_view);
        
        //Get SharedPreferences
        final SharedPreferences preferences = Preferences.getPreferences(this);
        nickname = preferences.getString("nickname", ""); 
        serverhost = preferences.getString("serverhost", "");
        serverport = Integer.valueOf(preferences.getString("serverport", "0"));
        myport = preferences.getString("myport", "");
        comm = Communication.getInstance(serverhost, new Integer(myport).intValue(), new Integer(serverport).intValue());
        groupname = getIntent().getStringExtra("Groupname");

     // Initialize ListView-Users and register ContextMenu
        lv = (ListView)findViewById(R.id.listviewUsers);
        names = comm.getUserNames(groupname);
        
        //comm.updateGroup(groupname, nickname);
        ArrayList<String> memberTempList = new ArrayList<String>();
        for(int i= 0; i < names.length; i++)
        	memberTempList.add(names[i]);
        
      
        arrayAdapter = new ArrayAdapter<String>(this, R.layout.user_list, R.id.user, memberTempList);
        lv.setAdapter(arrayAdapter);
        
        Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
            	
            	Log.d("GET MESSAGE", "YUHU");
             
            	String msgString = (String)msg.obj;
            	
            	String[] msgArray = msgString.split(",");
            	
            	
            	if(msgArray[0].equals("UMLVNM")) {	
            		
            		Toast.makeText(getApplicationContext(), "New Member "+msgArray[1]+" Joined", Toast.LENGTH_LONG).show();
                   	arrayAdapter.insert(msgArray[1], 1);
                   	arrayAdapter.notifyDataSetChanged();
                   	
            	}
            	
            	 if(msgArray[0].equals("UMLVDM")) {	
            		
            		if(msgArray[1].equals(nickname)) {
                   		Toast.makeText(getApplicationContext(), "YOU HAVE BEEN KICKED BY THE TALKMASTER", Toast.LENGTH_LONG).show();
                   		comm.shutDown();
                   		finish();
                   	}	
            		else {
            			Toast.makeText(getApplicationContext(), "Member "+msgArray[1]+" quits", Toast.LENGTH_LONG).show();
            			arrayAdapter.remove(msgArray[1]);
            			arrayAdapter.notifyDataSetChanged();
            		}
                   	
                   	
                   	
                   	
            	}
            	
            	 if(msgArray[0].equals("WU")) {	
            		
            		Toast.makeText(getApplicationContext(), "YOU HAVE BEEN WARNED BY THE TALKMASTER.", Toast.LENGTH_LONG).show();
                   //	arrayAdapter.remove(msgArray[1]);
                   //	arrayAdapter.notifyDataSetChanged();
            		
            		                  	
            	}

            	if(msgArray[0].equals("LSPR")) {
					
            		Toast.makeText(getApplicationContext(), "You lost the speech right", Toast.LENGTH_LONG).show();

					
				}	
				
				
				if(msgArray[0].equals("GSPR")) {
					
            		Toast.makeText(getApplicationContext(), "You have the floor", Toast.LENGTH_LONG).show();

					
				}		
            	
            	 if(msgArray[0].equals("CG")) {	
            		
            		Toast.makeText(getApplicationContext(), "Master quits, closing group", Toast.LENGTH_LONG).show();
                   //	arrayAdapter.remove(msgArray[1]);
                   //	arrayAdapter.notifyDataSetChanged();
            		
            		comm.shutDown();
            		finish();
                   	
            	}
            	
            	 if(msgArray[0].equals("KU")) {	
            		
            		Toast.makeText(getApplicationContext(), "YOU HAVE BEEN KICKED BY THE TALKMASTER", Toast.LENGTH_LONG).show();
                   //	arrayAdapter.remove(msgArray[1]);
                   //	arrayAdapter.notifyDataSetChanged();
            		
            		comm.shutDown();
            		finish();
                   	
            	}

            }
         };
         if(streamHandler == null) {
          streamHandler = new StreamHandler(serverhost, new Integer(myport).intValue(), new Integer(serverport).intValue(), nickname, groupname, memberList, handler);
      		streamHandler.start();
    	 Log.d("THREAD", ""+streamHandler.getId());
         }
        
        // Initialize AlertDialog-Box for Back-Key with "YES"- and "NO"-option
                builder = new AlertDialog.Builder(this);
                builder.setTitle(R.string.alert_title);
                builder.setMessage(R.string.alert_msg_user);
                builder.setPositiveButton("Yes", new OnClickListener(){
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                                
                        		streamHandler.killThread();
                        		comm.leaveGroup(groupname, nickname);
                        		comm.shutDown();
                        		
                                finish();
                                System.exit(0);
                            	
                                
                                
                                
                                
                                
                        		//startActivity(new Intent(getApplicationContext(), Main.class));
                        }
                });
                builder.setNegativeButton("No", new OnClickListener(){
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                        }
                });
                
                //public StreamHandler(String serverAdress, int serverPort, int myPort, String nickname, String groupname) {
                
                
        }

        public boolean onKeyDown(int keyCode, KeyEvent event)  {
            if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                Log.d("TAG", "BACK");
                AlertDialog alert = builder.create();
                alert.show();
                return true;
            }
            return super.onKeyDown(keyCode, event);
        }

        }
       
       

